package com.etong.citymap.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.etong.citymap.bean.AssignmentBean;
import com.etong.citymap.bean.ImageBean;
import com.etong.citymap.bean.ViewHolder;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.impl.SentenceDaoImp;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.module.SentenceBean;
import com.etong.citymap.util.ImageLoader;
import com.etong.citymap.util.Status;
import com.etong.citymap.util.log.LogUtil;

/**
 * 我的任务，核查和核实
 */
public class MyAssignmentActivity extends Activity implements OnClickListener,
		OnItemClickListener, OnScrollListener {
	ListView listView;
	ListView listView_heshi;
	AlertDialog load;
	LinearLayout mytype_t1;
	LinearLayout mytype_t2;
	LinearLayout my_back;
	LinearLayout mu_refresh;
	private int pageindex=0;
	private int recordCount;
	private ImageLoader mImageLoader=new ImageLoader(this);
	private int getLastVisiblePosition;
	private int lastVisiblePositionY;
	private static ArrayList<AssignmentBean> assignmentBeans;
	private static ArrayList<AssignmentBean> assignmentBeans_heshi;
	private CityApplication cityApplication;
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				load.dismiss();
				String result = msg.getData().getString("result");
				if (result.equals("-2")) {
					Toast.makeText(MyAssignmentActivity.this, "没有新任务",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-1")) {
					Toast.makeText(MyAssignmentActivity.this, "数据库异常",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-3")) {
					Toast.makeText(MyAssignmentActivity.this, "未知错误，获取失败",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-4")) {
					Toast.makeText(MyAssignmentActivity.this, "已在其他机器登录",
							Toast.LENGTH_SHORT).show();
				}else if (result.equals("-7")) {
					Toast.makeText(MyAssignmentActivity.this, "数据解析异常！",
							Toast.LENGTH_SHORT).show();
				}

				listView.setAdapter(baseAdapter);
				listView_heshi.setAdapter(baseAdapter_heshi);
			} else if (msg.what == 3) {
				load.dismiss();
				listView.setAdapter(baseAdapter);
				listView_heshi.setAdapter(baseAdapter_heshi);
			} else if (msg.what == 5) {
				ImageView imageView = (ImageView) msg.obj;
				imageView.setImageBitmap((Bitmap) msg.getData().getParcelable(
						"bitmap"));
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.assignment);
		cityApplication = (CityApplication)getApplication();
		assignmentBeans = new ArrayList<AssignmentBean>();
		assignmentBeans_heshi = new ArrayList<AssignmentBean>();
		load = new ProgressDialog(this);
		load.setTitle(null);
		load.setMessage("请稍等,正在加载数据...");
		load.setCanceledOnTouchOutside(false);
		init();
	}

	@Override
	protected void onResume() {
		pageindex=0;
		assignmentBeans.clear();
		loading();
		super.onResume();
	}

	void loading() {
		load.show();
		new Loading();
	}

	void init() {
		listView = (ListView) findViewById(R.id.myassignmentlist);
		listView_heshi = (ListView) findViewById(R.id.myassignmentlist_heshi);
		mytype_t1 = (LinearLayout) findViewById(R.id.mytype_t1);
		mytype_t2 = (LinearLayout) findViewById(R.id.mytype_t2);
		my_back = (LinearLayout) findViewById(R.id.my_back);
		mu_refresh = (LinearLayout) findViewById(R.id.mu_refresh);
		mu_refresh.setOnClickListener(this);
		mytype_t1.setOnClickListener(this);
		mytype_t2.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);
		listView_heshi.setOnItemClickListener(this);
		my_back.setOnClickListener(this);
	}
	class Loading extends Thread {
		public Loading() {
			start();
		}

		@Override
		public void run() {

			SentenceDaoImp sentenceDaoImp = new SentenceDaoImp(MyAssignmentActivity.this);
			List<SentenceBean> sentenceBeans = sentenceDaoImp.findHCHS();
			String url = "supervisor/ashx/TaskListnew.ashx"; // 001 001
			Map<String, String> map = new HashMap<String, String>();
			map.put("superid", cityApplication.getUserId());
			map.put("code", cityApplication.getUserCode());
			map.put("pageindex", pageindex + "");
			map.put("pagecount", cityApplication.PageCount + "");
			try {
				Long t1 = System.currentTimeMillis();
				String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
				Long t2 = System.currentTimeMillis();
				System.out.println(t2-t1);
				if (result.equals("-1") || result.equals("-2")
						|| result.equals("-3") || result.equals("-4")) {
					Message message = new Message();
					message.getData().putString("result", result);
					message.what = 2;
					handler.sendMessage(message);
				} else {
					JSONArray jsonArray = new JSONArray(result);
					for (int i = 0; i < jsonArray.length(); i++) {
						AssignmentBean assignmentBean = new AssignmentBean();
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						String prjid=jsonObject.getString("prjid");
						assignmentBean.setUpload(false);
						for(SentenceBean sb : sentenceBeans){
							if(sb.getPrjid().equals(prjid)){
								assignmentBean.setUpload(true);
								break;
							}
						}
						assignmentBean.setPrjid(prjid);
						assignmentBean.setType(jsonObject.getString("type"));
						recordCount = jsonObject.getInt("recordCount");
						assignmentBean.setBigclass(jsonObject.getString("bigclass"));
						assignmentBean.setPrjname(jsonObject.getString("prjname"));
						assignmentBean.setSmallclass(jsonObject	.getString("smallclass"));
						assignmentBean.setSituation(jsonObject.getString("situation"));
						assignmentBean.setPrjcheckid(jsonObject.getString("prjcheckid"));
						assignmentBean.setCreatetime(jsonObject.getString("createtime"));
						assignmentBean.setFlag(jsonObject.getInt("flag"));
						assignmentBean.setX(jsonObject.getString("x"));
						assignmentBean.setY(jsonObject.getString("y"));
						JSONArray pt1 = jsonObject.getJSONArray("photo1");
						JSONArray pt2 = jsonObject.getJSONArray("photo2");
						JSONArray pt3 = jsonObject.getJSONArray("photo3");
						String[] ptv1 = new String[pt1.length()];
						String[] ptv2 = new String[pt2.length()];
						String[] ptv3 = new String[pt3.length()];
						for (int t = 0; t < pt1.length(); t++) {
							ptv1[t] = pt1.getString(t);
						}
						for (int t = 0; t < pt2.length(); t++) {
							ptv2[t] = pt2.getString(t);
						}
						for (int t = 0; t < pt3.length(); t++) {
							ptv3[t] = pt3.getString(t);
						}
						assignmentBean.setPhoto1(ptv1);
						assignmentBean.setPhoto2(ptv2);
						assignmentBean.setPhoto3(ptv3);
						if (assignmentBean.getFlag() == Status.ProjectType_HS) {
							assignmentBeans_heshi.add(assignmentBean);
						} else {
							assignmentBeans.add(assignmentBean);
						}
					}
					System.out.println(System.currentTimeMillis()-t1);
					Message message = new Message();
					message.what = 3;
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				Message message = new Message();
				message.getData().putString("result", "-7");
				message.what = 2;
				handler.sendMessage(message);
				LogUtil.e(e);
			}
		}
	}

	public BaseAdapter baseAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {

			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(MyAssignmentActivity.this)
						.inflate(R.layout.listitem, null);
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.listitem_icon);
				ImageView icon_top = (ImageView) convertView
						.findViewById(R.id.listitem_icon_top);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem_date);
				TextView content = (TextView) convertView
						.findViewById(R.id.listitem_content);
				vHolder = new ViewHolder();
				vHolder.setContent(content);
				vHolder.setDate(date);
				vHolder.setTitle(title);
				vHolder.setIcon(icon);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (assignmentBeans != null) {
				AssignmentBean notesBean = assignmentBeans.get(position);
				String imgUrl = "";
				if(notesBean.getPhoto1().length>0) 
					imgUrl = notesBean.getPhoto1()[0];
				String s = "";
				if(notesBean.isUpload()){
					s = "正在上传－";
				}
				vHolder.getTitle().setText(notesBean.getPrjname());
				vHolder.getDate().setText(notesBean.getCreatetime());
				if(notesBean.isUpload()){
					vHolder.getContent().setTextColor(Color.RED);
				}
				vHolder.getContent().setText(s+notesBean.getSituation());
				ImageView imageView = vHolder.getIcon();
				mImageLoader.DisplayImage(imgUrl, imageView, false);
			}
			return convertView;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public int getCount() {
			return assignmentBeans.size();
		}
	};
	public BaseAdapter baseAdapter_heshi = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(MyAssignmentActivity.this)
						.inflate(R.layout.listitem, null);
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.listitem_icon);
				ImageView icon_top = (ImageView) convertView
						.findViewById(R.id.listitem_icon_top);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem_date);
				TextView content = (TextView) convertView
						.findViewById(R.id.listitem_content);
				vHolder = new ViewHolder();
				vHolder.setContent(content);
				vHolder.setDate(date);
				vHolder.setTitle(title);
				vHolder.setIcon(icon);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (assignmentBeans != null) {
				AssignmentBean notesBean = assignmentBeans.get(position);
				String imgUrl = notesBean.getPhoto1()[0];
				String s = "";
				if(notesBean.isUpload()){
					s = "正在上传－";
				}
				vHolder.getTitle().setText(notesBean.getPrjname());
				vHolder.getDate().setText(notesBean.getCreatetime());
				if(notesBean.isUpload()){
					vHolder.getContent().setTextColor(Color.RED);
				}
				vHolder.getContent().setText(s+notesBean.getSituation());
				ImageView imageView = vHolder.getIcon();
				mImageLoader.DisplayImage(imgUrl, imageView, false);
			}
			return convertView;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public int getCount() {
			return assignmentBeans_heshi.size();
		}
	};

	@Override
	public void onClick(View v) {
		if (mytype_t1 == v) {
			mytype_t1.setBackgroundResource(R.drawable.mytypeback_down);
			mytype_t2.setBackgroundResource(R.drawable.mytypeback);
			listView.setVisibility(LinearLayout.VISIBLE);
			listView_heshi.setVisibility(LinearLayout.GONE);
		}
		if (mytype_t2 == v) {
			mytype_t2.setBackgroundResource(R.drawable.mytypeback_down);
			mytype_t1.setBackgroundResource(R.drawable.mytypeback);
			listView.setVisibility(LinearLayout.GONE);
			listView_heshi.setVisibility(LinearLayout.VISIBLE);
		}
		if (my_back == v) {
			finish();
		}
		if (mu_refresh == v) {
			pageindex = 0;
			assignmentBeans.clear();
			loading();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) { // 13274347520
		if (listView == parent || listView_heshi == parent) {
			//Configure.ImageList=null;
			cityApplication.setImageList(null);
			AssignmentBean bean = assignmentBeans.get(position);
			if(bean.isUpload()){
				Toast.makeText(MyAssignmentActivity.this,	"该数据正在后台上传！请不要重复提交！", Toast.LENGTH_SHORT).show();
				pageindex = 0;
				assignmentBeans.clear();
				loading();
				return;
			}
			String[] t1 = bean.getPhoto1();
			String[] t2 = bean.getPhoto2();
			String[] t3 = bean.getPhoto3();
			ImageBean[] ilns = new ImageBean[t1.length + t2.length	+ t3.length];
			int postion = 0;
			for (int i = 0; i < t1.length; i++) {
				ilns[postion] = new ImageBean();
				ilns[postion].setIsSelect(true);
				ilns[i].setUrlpath(t1[i]);
				String name = t1[i].substring(t1[i].lastIndexOf("/") + 1,t1[i].length());
				ilns[postion].setPathname(name);
				ilns[postion] .setType(Status.ProjectType_SB);
				postion++;
			}

			for (int i = 0; i < t2.length; i++) {
				ilns[postion] = new ImageBean();
				ilns[postion].setIsSelect(true);
				ilns[postion].setUrlpath(t2[i]);
				String name = t2[i].substring(t2[i].lastIndexOf("/") + 1,t2[i].length());
				ilns[postion].setPathname(name);
				ilns[postion] .setType(Status.ProjectType_HC);
				postion++;
			}

			for (int i = 0; i < t3.length; i++) {
				ilns[postion] = new ImageBean();
				ilns[postion].setIsSelect(true);
				ilns[postion].setUrlpath(t3[i]);
				ilns[postion] .setType(Status.ProjectType_HS);
				String name = t3[i].substring(t3[i].lastIndexOf("/") + 1,t3[i].length());
				ilns[postion].setPathname(name);
				postion++;
			}
			cityApplication.setImageList_Net(ilns);
			Intent intent = new Intent(this, ProblemUploadActivity.class);
			intent.putExtra("bean", bean);
			startActivity(intent);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		if (view == listView) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
					View v = (View) view.getChildAt(view.getChildCount() - 1);
					int[] location = new int[2];
					v.getLocationOnScreen(location);
					int y = location[1];
					if (view.getLastVisiblePosition() != getLastVisiblePosition
							&& lastVisiblePositionY != y) {
						getLastVisiblePosition = view.getLastVisiblePosition();
						lastVisiblePositionY = y;
						return;
					} else if (view.getLastVisiblePosition() == getLastVisiblePosition
							&& lastVisiblePositionY == y)// 第二次拖至底部
					{
						if (recordCount > assignmentBeans.size()) {
							pageindex++;
							loading();
						} else {
							Toast.makeText(MyAssignmentActivity.this,
									"已经没有可以加载的数据了", Toast.LENGTH_SHORT).show();
						}
					}
				}

				getLastVisiblePosition = 0;
				lastVisiblePositionY = 0;
			}

		}

	}
}
